using System;
using Sirenix.Serialization;
using UnityEngine;
using UnityEngine.UI;
using XLua;

[LuaCallCSharp]
public sealed class LuaFormLogic : UGuiFrom
{
    internal static Action<LuaFormLogic> __CallbackForLua;

    public Action luaOpen = null,
        luaUpdate = null,
        luaClose = null,
        luaCover = null,
        luaPause = null,
        luaRefocus = null,
        luaResume = null,
        luaReveal = null;

    protected override void OnInit(object userData)
    {
        base.OnInit(userData);
        
        Debug.Log("this.type = "+this.GetType());

        // if (string.IsNullOrEmpty(luaFormText))
        //     return;
        //
        // scriptEnv = EntityInst.Lua.Env.NewTable();
        // // 为每个脚本设置一个独立的环境，可一定程度上防止脚本间全局变量、函数冲突
        // LuaTable meta = EntityInst.Lua.Env.NewTable();
        // meta.Set("__index", EntityInst.Lua.Env.Global);              
        // scriptEnv.SetMetaTable(meta);
        // meta.Dispose();
        //
        // scriptEnv.Set("self", this);
        //
        // EntityInst.Lua.Env.DoString(ta.text, "luaForm", scriptEnv);
        //
        // scriptEnv.Get("OnOpen", out luaOpen);
        // scriptEnv.Get("OnClose", out luaClose);
        // scriptEnv.Get("OnUpdate", out luaUpdate);
        // scriptEnv.Get("OnCover", out luaCover);
        // scriptEnv.Get("OnPause", out luaPause);
        // scriptEnv.Get("OnRefocus", out luaRefocus);
        // scriptEnv.Get("OnResume", out luaResume);
        // scriptEnv.Get("OnReveal", out luaReveal);
    }

    protected override void OnUpdate(float elapseSeconds, float realElapseSeconds)
    {
        base.OnUpdate(elapseSeconds, realElapseSeconds);
        
        luaUpdate?.Invoke();
    }

    protected override void OnOpen(object userData)
    {
        __CallbackForLua?.Invoke(this);
        __CallbackForLua = null;
        
        base.OnOpen(userData);

        luaOpen?.Invoke();
    }

    protected override void OnClose(bool isShutdown, object userData)
    {
        base.OnClose(isShutdown, userData);
        
        luaClose?.Invoke();
    }

    protected override void OnCover()
    {
        base.OnCover();
        
        luaCover?.Invoke();
    }

    protected override void OnPause()
    {
        base.OnPause();
        
        luaPause?.Invoke();
    }

    protected override void OnRecycle()
    {
        base.OnRecycle();
        
        luaOpen = null;
        luaUpdate = null;
        luaClose = null;
        luaCover = null;
        luaPause = null;
        luaRefocus = null;
        luaResume = null;
        luaReveal = null;
    }

    protected override void OnRefocus(object userData)
    {
        base.OnRefocus(userData);
        
        luaRefocus?.Invoke();
    }

    protected override void OnResume()
    {
        base.OnResume();
        
        luaResume?.Invoke();
    }

    protected override void OnReveal()
    {
        base.OnReveal();
        
        luaReveal?.Invoke();
    }
}